package cn.t.service.common;


import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.StringWriter;
import java.lang.invoke.MethodHandles;
import java.util.HashMap;


@Component
public class PdfComponent {

    private final static Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
    /**
     * 模板配置类
     */
    @Resource
    private Configuration freemarkerCfg;
    /**
     * @param data         渲染数据
     * @param templateName 模板名称
     * @return 字符串
     */
    public String getTemplate(HashMap<String, Object> data, String templateName) {
        try (StringWriter out = new StringWriter()) {
            //获取模版
            Template template = freemarkerCfg.getTemplate(templateName);
            template.process(data, out);
            out.flush();
            String templateContent = out.getBuffer().toString();
            // 处理特殊字符
            templateContent = templateContent
                    .replaceAll("&", "&amp;")
                    .replaceAll("\u0002", " ")
                    .replaceAll("<=", "≤")
                    .replaceAll(">=", "≥");
            return templateContent;
        } catch (Exception e) {
            log.error("渲染 html 失败：", e);
            return null;
        }
    }

}
